<template>
  <div class="vehicle-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">车辆信息管理系统</h1>
	            <p class="sub-title">每一条车辆信息都是责任的载体，每一次管理都是安全的守护，用专业让车辆管理更精准、更可靠</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="车辆详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="车辆信息" direction="vertical" :column="1" :model="detailData" border>
        <el-descriptions-item label="编号">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ detailData.licensePlate }}</el-descriptions-item>
        <el-descriptions-item label="登记照片">
          <img 
            v-if="detailData.registrationPhoto" 
            :src="'data:image/png;base64,' + detailData.registrationPhoto" 
            alt="车辆登记照" 
            class="detail-image"
          >
          <span v-else>无照片</span>
        </el-descriptions-item>
        <el-descriptions-item label="关联住户ID">{{ detailData.residentId }}</el-descriptions-item>
        <el-descriptions-item label="住户姓名">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="住户联系方式">{{ detailData.contactInfo }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑车辆"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆ID" prop="id">
              <el-input v-model="ruleForm.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-model="ruleForm.licensePlate"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="登记照片" prop="registrationPhoto">
              <!-- 图片预览 -->
              <div v-if="ruleForm.registrationPhoto" class="photo-preview">
                <img :src="ruleForm.registrationPhoto" alt="预览图" class="preview-img">
              </div>
              
              <!-- 上传按钮 -->
              <el-button @click="triggerUpload('edit')" type="primary" size="mini" class="upload-btn">
                本地上传
                <input
                  type="file"
                  accept="image/*"
                  hidden
                  ref="editPhotoFile"
                  @change="handleFileChange($event, 'edit')"
                />
              </el-button>
              
              <!-- 拍照上传功能已注释
              <el-button @click="openCamera('edit')" type="success" size="mini" class="upload-btn">
                拍照上传
              </el-button>
              -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="住户ID" prop="residentId">
              <el-input v-model.number="ruleForm.residentId" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前住户" prop="name">
              <el-input v-model="ruleForm.name" disabled placeholder="关联住户信息"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 摄像头区域已注释
        <div v-if="showCamera.edit" class="camera-container">
          <video 
            id="editVideo" 
            autoplay 
            playsinline 
            class="camera-video"
          ></video>
          <canvas id="editCanvas" class="camera-canvas"></canvas>
          <div class="camera-btns">
            <el-button @click="capturePhoto('edit')" type="primary" size="mini">拍照</el-button>
            <el-button @click="closeCamera('edit')" type="danger" size="mini">关闭</el-button>
          </div>
        </div>
        -->

        <el-form-item>
          <el-button type="primary" @click="submitEdit">确定</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="添加车辆"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="addRules" 
        ref="addFormRef" 
        label-width="100px" 
        class="demo-addForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-model="addForm.licensePlate" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="登记照片">
              <!-- 图片预览 -->
              <div v-if="addForm.registrationPhoto" class="photo-preview">
                <img :src="addForm.registrationPhoto" alt="预览图" class="preview-img">
              </div>
              
              <!-- 上传按钮 -->
              <el-button @click="triggerUpload('add')" type="primary" size="mini" class="upload-btn">
                本地上传
                <input
                  type="file"
                  accept="image/*"
                  hidden
                  ref="addPhotoFile"
                  @change="handleFileChange($event, 'add')"
                />
              </el-button>
              
              <!-- 拍照上传功能已注释
              <el-button @click="openCamera('add')" type="success" size="mini" class="upload-btn">
                拍照上传
              </el-button>
              -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="住户ID" prop="residentId">
              <el-input 
                v-model.number="addForm.residentId" 
                type="number" 
                placeholder="请输入关联的住户ID"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 摄像头区域已注释
        <div v-if="showCamera.add" class="camera-container">
          <video 
            id="addVideo" 
            autoplay 
            playsinline 
            class="camera-video"
          ></video>
          <canvas id="addCanvas" class="camera-canvas"></canvas>
          <div class="camera-btns">
            <el-button @click="capturePhoto('add')" type="primary" size="mini">拍照</el-button>
            <el-button @click="closeCamera('add')" type="danger" size="mini">关闭</el-button>
          </div>
        </div>
        -->

        <el-form-item>
          <el-button type="primary" @click="submitAdd">确定</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 数据展示与操作区域 -->
    <el-row>
      <el-row :gutter="20" style="width: 100%; margin-bottom: 20px;">
        <el-col :span="7">
          <el-input 
            placeholder="请输入车牌号搜索" 
            v-model="searchQuery" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="7">
          <el-input 
            placeholder="请输入住户ID搜索" 
            v-model.number="residentIdQuery" 
            type="number"
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="2" :offset="1" class="text-right">
          <el-button type="success" icon="el-icon-plus" @click="openDetails2">添加车辆</el-button>
        </el-col>
      </el-row>

      <!-- 关键修改：表格数据绑定为「当前页数据」currentPageData -->
      <el-table 
        :data="currentPageData" 
        border 
        style="width: 100%;"
        height="450"
        stripe
      >
        <el-table-column prop="id" label="编号" width="150" align="center"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="270" align="center"></el-table-column>
        <el-table-column prop="registrationPhoto" label="登记照片" width="280" align="center">
          <template #default="scope">
            <img 
              v-if="scope.row.registrationPhoto" 
              :src="'data:image/png;base64,' + scope.row.registrationPhoto" 
              alt="车辆照片" 
              class="table-image"
              @click="previewImage(scope.row.registrationPhoto)"
            >
            <span v-else>无照片</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="住户姓名" width="180" align="center"></el-table-column>
        <el-table-column prop="contactInfo" label="住户联系方式" width="290" align="center"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDetails(scope.row)">查看</el-button>
            <el-button type="warning" size="small" @click="openDetails1(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteVehicle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredTableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="50%"
    >
      <img :src="previewImageUrl" alt="预览" class="preview-large">
    </el-dialog>
  </div>
</template>

<script setup>
// 关键修改1：导入computed用于计算当前页数据
import { ref, reactive, onMounted, toRefs, getCurrentInstance, computed } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 对话框控制
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const previewVisible = ref(false)

// 数据与分页
const searchQuery = ref('')
const residentIdQuery = ref(null) // 住户ID查询条件
const currentPage = ref(1)
const pageSize = ref(10)
const tableData = ref([])
const filteredTableData = ref([])

// 关键修改2：计算当前页要显示的数据（核心分页逻辑）
const currentPageData = computed(() => {
  // 计算起始索引：(当前页-1) * 每页条数
  const startIndex = (currentPage.value - 1) * pageSize.value
  // 从过滤后的数据中截取当前页数据：slice(起始索引, 起始索引+每页条数)
  return filteredTableData.value.slice(startIndex, startIndex + pageSize.value)
})

// 详情数据
const detailData = reactive({
  id: '',
  licensePlate: '',
  registrationPhoto: '',
  residentId: '',
  name: '',
  contactInfo: ''
})

// 编辑表单
const ruleForm = reactive({
  id: '',
  licensePlate: '',
  registrationPhoto: '',
  residentId: null,
  name: '',
  contactInfo: ''
})

// 新增表单
const addForm = reactive({
  licensePlate: '',
  registrationPhoto: '',
  residentId: null
})

// 摄像头控制相关代码已注释
// const showCamera = reactive({
//   add: false,
//   edit: false
// })
// const streamRef = ref(null)

// 图片预览
const previewImageUrl = ref('')

// 表单验证规则
const rules = reactive({
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  residentId: [
    { required: true, message: '请输入住户ID', trigger: 'blur' },
    { type: 'number', message: '住户ID必须为数字', trigger: 'blur' }
  ]
})

// 修改点4：移除新增表单中照片的必填验证
const addRules = reactive({
  ...rules
  // 移除registrationPhoto的验证规则，使其变为非必填
})

// 组件实例
const { proxy } = getCurrentInstance()

// 格式化图片为后端需要的格式（去除base64前缀）
const formatImageForBackend = (base64Str) => {
  if (!base64Str) return null
  return base64Str.replace(/^data:image\/\w+;base64,/, '')
}

// 触发文件上传
const triggerUpload = (type) => {
  if (type === 'add') {
    proxy.$refs.addPhotoFile.click()
  } else {
    proxy.$refs.editPhotoFile.click()
  }
}

// 处理文件上传
const handleFileChange = (e, type) => {
  const file = e.target.files[0]
  if (!file) return

  if (!/image\/(png|jpg|jpeg|gif)/.test(file.type)) {
    ElMessage.warning('请选择图片文件（png、jpg、jpeg、gif）')
    return
  }

  const reader = new FileReader()
  reader.onload = (ev) => {
    if (type === 'add') {
      addForm.registrationPhoto = ev.target.result
    } else {
      ruleForm.registrationPhoto = ev.target.result
    }
  }
  reader.readAsDataURL(file)

  // 清空输入，允许重复选择同一文件
  e.target.value = ''
}

// 摄像头相关方法已注释
// 打开摄像头
// const openCamera = (type) => {
//   showCamera[type] = true
//   const videoId = type === 'add' ? 'addVideo' : 'editVideo'
//   const video = document.getElementById(videoId)

//   navigator.mediaDevices.getUserMedia({ video: true })
//     .then(stream => {
//       video.srcObject = stream
//       streamRef.value = stream
//     })
//     .catch(err => {
//       ElMessage.error('无法访问摄像头：' + err.message)
//       showCamera[type] = false
//     })
// }

// 关闭摄像头
// const closeCamera = (type) => {
//   if (streamRef.value) {
//     streamRef.value.getTracks().forEach(track => track.stop())
//     streamRef.value = null
//   }
//   showCamera[type] = false
// }

// 拍照
// const capturePhoto = (type) => {
//   const videoId = type === 'add' ? 'addVideo' : 'editVideo'
//   const canvasId = type === 'add' ? 'addCanvas' : 'editCanvas'
  
//   const video = document.getElementById(videoId)
//   const canvas = document.getElementById(canvasId)
//   const ctx = canvas.getContext('2d')

//   // 设置canvas尺寸与视频一致
//   canvas.width = video.videoWidth
//   canvas.height = video.videoHeight
//   ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

//   // 获取base64图片
//   const base64Str = canvas.toDataURL('image/jpeg')
  
//   // 赋值给表单并关闭摄像头
//   if (type === 'add') {
//     addForm.registrationPhoto = base64Str
//   } else {
//     ruleForm.registrationPhoto = base64Str
//   }
  
//   closeCamera(type)
// }

// 预览图片
const previewImage = (base64Str) => {
  previewImageUrl.value = 'data:image/png;base64,' + base64Str
  previewVisible.value = true
}

// 查看详情
const openDetails = (row) => {
  Object.assign(detailData, row)
  dialogVisible.value = true
}

// 打开编辑
const openDetails1 = (row) => {
  ruleForm.id = row.id
  ruleForm.licensePlate = row.licensePlate
  ruleForm.registrationPhoto = row.registrationPhoto ? 'data:image/png;base64,' + row.registrationPhoto : ''
  ruleForm.residentId = row.residentId
  ruleForm.name = row.name
  ruleForm.contactInfo = row.contactInfo
  dialogVisible1.value = true
}

// 打开新增
const openDetails2 = () => {
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'residentId' ? null : ''
  })
  dialogVisible2.value = true
}

// 分页处理（无需修改，计算属性会自动响应currentPage和pageSize变化）
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页条数时，重置到第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val // 切换页码时，更新当前页
}

// 搜索处理 - 增加了住户ID查询条件
const handleSearch = () => {
  const query = searchQuery.value.trim().toLowerCase()
  const residentId = residentIdQuery.value
  
  if (!query && !residentId) {
    filteredTableData.value = [...tableData.value]
  } else {
    filteredTableData.value = tableData.value.filter(item => {
      // 车牌号过滤
      const matchLicense = query ? item.licensePlate.toLowerCase().includes(query) : true
      // 住户ID过滤
      const matchResidentId = residentId ? item.residentId === residentId : true
      // 同时满足两个条件
      return matchLicense && matchResidentId
    })
  }
  currentPage.value = 1 // 搜索后重置页码到第一页
}

// 提交编辑
const submitEdit = () => {
  proxy.$refs.ruleFormRef.validate((valid) => {
    if (!valid) return

    // 准备提交数据
    const submitData = {
      vehicleId: ruleForm.id,
      licensePlate: ruleForm.licensePlate,
      residentId: ruleForm.residentId,
      registrationPhoto: formatImageForBackend(ruleForm.registrationPhoto)
    }

    post('/sc/vehicles/updateVehicleInfo', submitData, (res) => {
      if (res.status === 1) {
        ElMessage.success('修改成功！')
        dialogVisible1.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    })
  })
}

// 提交新增
const submitAdd = () => {
  proxy.$refs.addFormRef.validate((valid) => {
    if (!valid) return

    // 准备提交数据
    const submitData = {
      licensePlate: addForm.licensePlate,
      residentId: addForm.residentId,
      registrationPhoto: formatImageForBackend(addForm.registrationPhoto)
    }

    post('/sc/vehicles/addVehicleInfo', submitData, (res) => {
      if (res.status === 1) {
        ElMessage.success('添加成功！')
        dialogVisible2.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 删除车辆
const deleteVehicle = (row) => {
  ElMessageBox.confirm(
    `确定要删除车牌号为【${row.licensePlate}】的车辆信息吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    post('/sc/vehicles/deleteVehicleInfo', { vehicleId: row.id }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除
  })
}

// 获取车辆列表
const fetchTableData = () => {
  post('/sc/vehicles/getAllVehicleInfo', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data || []
      filteredTableData.value = [...tableData.value]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      tableData.value = []
      filteredTableData.value = []
    }
  })
}

// 初始化
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.vehicle-container {
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.text-right {
  display: flex;
  justify-content: flex-end;
}

.table-image {
  width: 80px;
  height: 60px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 4px;
}

.detail-image {
  max-width: 300px;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.preview-img {
  width: 150px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 10px;
  border-radius: 4px;
}

.preview-large {
  width: 100%;
  height: auto;
  max-height: 500px;
  object-fit: contain;
}

.photo-preview {
  margin-bottom: 10px;
}

.upload-btn {
  margin-right: 10px;
}

/* 摄像头相关样式已注释
.camera-container {
  margin: 10px 0;
  text-align: center;
}

.camera-video, .camera-canvas {
  width: 320px;
  height: 240px;
  border: 1px solid #ccc;
  margin: 0 auto 10px;
  display: block;
}

.camera-btns {
  display: flex;
  justify-content: center;
  gap: 10px;
}
*/
</style>